package http

import (
	"fmt"
	"io"
	"net/http"

	log "github.com/sirupsen/logrus"
)

func EasyHttpRequest(method string, path string, headers map[string]string, body io.Reader) (*http.Response, error) {
	client := &http.Client{}
	req, err := http.NewRequest(method, path, body)
	if err != nil {
		log.Error(fmt.Sprintf("Exec http %s %s fail：%v", method, path, err))
		return nil, err
	}
	for k, v := range headers {
		req.Header.Set(k, v)
	}
	resp, err := client.Do(req)
	log.Info(fmt.Sprintf("Exec http %s %s,resp status %s,header %v", method, path, resp.Status, resp.Header))
	return resp, err
}

func EasyHttpGet(url string) []byte {
	// 发起请求
	res, err := http.Get(url)
	if err != nil {
		log.Error(fmt.Sprintf("Exec http get %s fail：%v", url, err))
	}
	// 延迟关闭（返回response的body尽量关闭,避免内存泄露）
	defer res.Body.Close()
	// 请求头 请求相应码
	log.Info(fmt.Sprintf("Exec http get %s,resp status %s,header %v", url, res.Status, res.Header))
	// 读取body数据
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Error(fmt.Sprintf("Read %s body fail：%v", url, err))
		return nil
	}
	return body
}

func EasyHttpPost(url string) []byte {
	// 发起请求
	res, err := http.Post(url, "application/x-www-form-urlencoded", nil)
	if err != nil {
		log.Error(fmt.Sprintf("Exec http Post %s fail：%v", url, err))
	}
	// 延迟关闭（返回response的body尽量关闭,避免内存泄露）
	defer res.Body.Close()
	// 请求头 请求相应码
	log.Info(fmt.Sprintf("Exec http Post %s,resp status %s,header %v", url, res.Status, res.Header))
	// 读取body数据
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Error(fmt.Sprintf("Read %s body fail：%v", url, err))
		return nil
	}
	return body
}
